var NS_SHOW_APPL_PAGES = "../Common/ShowApplImageFolder.aspx?"
var PAGE_FILE_NUM_NA = 0;
var PAGES_ALL = -1;
var PC_FROM = 0; //PageCount from
var PC_TO = 1;
var MSG_NO_APPL_ID = "No ApplicantID";
var DELAY_FAST = 100;
var DELAY_MEDIUM = 300;
var DELAY_SLOW = 500;
var featuresMail = "dialogHeight:300px; dialogWidth:400px; resizable:1; status:0; help:0";
initWS("Imaging","Imaging.asmx?WSDL");
var FL = null;
var Files;
var Folders;
var filesAreApplIDs = getParam("MenuID");
function onApplicantSelected(params){_applID(params.applID);}
function load_Page(){
	FL = document.all.divFolders;
	Files = document.all.divFiles;
	Folders = document.all.divFolders;
	focus();
	attachToApplicantSelected(onApplicantSelected);
	if( typeof(load_Page_NS) != 'undefined' )load_Page_NS();//execute custom onload code
	if( _applID() )Folders.colorImageFolders();
	//Debugger = showModelessDialog("/Include/Debugger.htm");
}
//************************************* Dragin' **************************************
function folderDrop(elTo,elFrom,copy){
	copy   = defined(copy) ? copy : this.dragCopy;
	elFrom = elFrom || this.dragElement;
	elTo   = elTo   || event.srcElement;
	clearSelection();
	if( this.move(elTo,elFrom,copy) === false )return;
	while( this.hist.Length )
		this.select(this.hist.Get(0,true),true);
	///Locals
}
// ***************************************** Images/Pages ******************************************
function moveOnServer(applID,fileIDFrom,pageNumbers,fileIDTo,pageAfter,copy){
	pageAfter = Math.max(pageAfter,0);
	var result = WS(CO("MoveFolderToFolder"),applID,fileIDFrom,pageNumbers,fileIDTo,pageAfter,copy);
	return showSOAPError(result) ? null : {to:result.value[PC_TO],from:result.value[PC_FROM]};
}
function moveThem(elTo,elFrom,copy){
	if( (FL.context(elTo).id == "divFolders" || FL.context(elFrom).id == "divFolders") && !_applID() )
		return alert(MSG_NO_APPL_ID) || false;
	var folderTo = this.fileID(elTo);
	var folderFrom = this.fileID(elFrom);
	var pageAfter = this.pageNum(elTo);
	var pageNumbers = this.pageNumbers(elFrom);
	var ds = moveOnServer(_applID(),folderFrom,pageNumbers,folderTo,pageAfter,copy);
	if( !ds )return false;
	this.afterShow(elFrom,elTo,pageNumbers,pageAfter);
	this.context(elTo).showPages(elTo,ds.to);
	if( !this.isBrother(elTo,elFrom) )
		this.context(elFrom).showPages(elFrom,ds.from);
}
function showNextFile(This,emptyElement){
	var e = emptyElement ? This.fileCont(emptyElement) : event.emptyCont;
	var next = This.nextFax(e);
	setTimeout(function(){if(e.parentElement)rsFromElement(e).Delete()},DELAY_SLOW);
	if( next && next.parentElement )next.click();
}
function showApplicant(){
	open("/Manager/Menu/ShowApplicant.aspx?ApplID="+_applID(),"APPLICANT_"+_applID());
}
function showFilePages(fileID,pageNumbers){
	if( filesAreApplIDs )return showApplIDPages(this.fileName(fileID));
	if( typeof(fileID) == "object" || fileID == undefined ){
		var e = fileID || selHist.Get();
		if( this.pageCount(e) == 0 )return;
		pageNumbers = pageNumbers || this.pageNumbers(e);
		fileID  = this.fileID(e);
	}
	var o = {fileName:fileID,pageNums:pageNumbers};
	var src = NS_SHOW_APPL_PAGES+makeQueryString(o);
	showImage(src);
}
function showApplPages(applID,folderID,pageNums){
	if( typeof(applID) == "object" || applID == undefined){
		var e = applID || selHist.Get();
		pageNums   = this.pageNumbers(e);
		folderID = this.fileID(e);
		applID = _applID();
	}
	if( !applID )return alert("No ApplicantID!");
	var o = {applID:applID,folderID:folderID,pageNums:pageNums,pdf:"pdf.pdf"};
	var src = NS_SHOW_APPL_PAGES+makeQueryString(o);
	showImage(src);
}
function showApplIDPages(applID){
	var o = {applID:parseInt(applID),folderID:0,PageNums:-1};
	var src = NS_SHOW_APPL_PAGES+makeQueryString(o);
	showImage(src);
}
function makeQueryString(o){
var i,a=new Array();
	for( i in o )
		a.push(i+"="+escape(o[i]));
	return a.join("&");
}
function showImage(src){
	var d = new Date();
	src += "&time="+d.valueOf();
	var sFrame = elIfrmPageParent.innerHTML;
	elIfrmPageParent.innerHTML = "";
	var src = 'src="'+httpEscape(src)+'"';
	sFrame = sFrame.replace(/src=\".*\"/i,src);
	elIfrmPageParent.innerHTML = sFrame;
	///Locals
	function httpEscape(s){return s;
		return s.replace(/[?]+([^?]+)$/,function($0,$1){return "?"+escape($1)}) }
}
function pageHistory(el){
	if( !_applID() )return alert("No ApplicantID!");
	var pageNum	= Folders.pageNum(el);
	var folderID	= Folders.fileID(el);
	var co = ws.createCallOptions("PageHistory",undefined,false);
	var ret = ws.Imaging.callService(co,_applID(),folderID,pageNum);
	if( showSOAPError(ret) )return;
	alert("Page was inserted by "+(ret.value||" John Doe"));
}
function deleteApplPage(e,This){
	if( !_applID() )return alert("No ApplicantID!");
	var pageNumbers = This.pageNumbers(e);
	if( !confirm(deleteMessage(This.fileName(e),pageNumbers)) )return;
	var result = WS(CO("DeleteApplPage"),_applID(),This.fileID(e),pageNumbers);
	if( showSOAPError(result) )return;
	This.afterShow(e,null,pageNumbers);
	This.showPages(e,result.value);
}
//******************************************* Context Menus *****************************************
function menuOut(){return;
	if( event.propertyName != "style.display" )	return;
	if( event.srcElement.style.display == "" )return;
	event.srcElement.contextFile.select(event.srcElement.contextElement,true);
}
	/****** Folder ******/
function menu_Page_Appl(This){
	var e = event.srcElement;
	var menu = new DropMenu("mnuFly");
	if( !menu.menuID )return false;
	menu.imageStyle += ";margin-top:0px;margin-bottom:0px";
	menu.add("E-Mail","mailFolder(ce)");
	if( This.hist.Get() && !This.isBrother(This.hist.Get(),e) ){
		menu.add("-","");
		menu.add("Move Here","pasteFolder(ce)");
		if( !This.isCousin(This.hist.Get(),e) )
			menu.add("Copy Here","pasteFolder(ce,true)");
	}
	menu.add("-","");
	menu.add("Move to New File","newFileFromFolder(ce)");
	menu.add("Copy to New File","newFileFromFolder(ce,true)");
	menu.add("-","");
	menu.add("History","pageHistory(ce)");
	menu.add("-","");
	menu.add(This.isPage(e)?"Delete":"Empty","deleteApplPage(ce,"+This.id+")");
	if( typeof(menu_Page_Appl_V) != "undefined" )menu_Page_Appl_V(menu,This);
	menu.menuShow(getLeftPos(getParentTR(event.srcElement)),event.y-event.offsetY+e.offsetHeight-3);
	event.cancelBubble = true;
	return false;
}
function pasteFolder(el,copy){
	FL.context(el).move(el,FL.hist.Get(),copy);
}
	/***** File *****/
function menu_Page(This){
	var e = event.srcElement;
	var del = This.isPage(e) ? "Page" : "File";
	var menu = new DropMenu("mnuFly");
	if( !menu.menuID )return false;
	menu.imageStyle += ";margin-top:0px;margin-bottom:0px";
	menu.add("E-Mail","mailFile(ce)");
	if( This.hist.Get() && !This.isBrother(This.hist.Get(),e) ){
		menu.add("-","");
		menu.add("Move Here","pasteFolder(ce)");
		menu.add("Copy Here","pasteFolder(ce,true)");
	}
	menu.add("-","");
	menu.add("Copy to New File","newFileFromFile(ce,true)");
	menu.add("Move to New File","newFileFromFile(ce)");
	menu.add("-","");
	menu.add("Delete "+del,"deleteFile(ce)");
	//		menu.addMenu("Show Page","showFilePages('"+fileName+"',"+pageNum+","+pageCount+")");
	if( typeof(menu_Page_V) != "undefined" )menu_Page_V(menu,This);
	menu.menuShow(getLeftPos(getParentTR(e)),event.y-event.offsetY+e.offsetHeight-3);
	event.cancelBubble = true;
	return false;
}
function newFileFromFolder(el,copy){
	if( !_applID() )return alert(MSG_NO_APPL_ID);
	var newFile = trim(prompt((copy?"Copy":"Move")+" page(s) to file:",newFileFromFile.newFile||"")||"");
	if( !newFile )return;
	newFileFromFile.newFile = newFile;
	if( newFile.match(/^[0-9]+$/) )newFile += "_";
	var pageNumbers = FL.pageNumbers(el);
	var ds = moveOnServer(_applID(),FL.fileID(el),pageNumbers,newFile,PAGES_ALL,copy);
	if( !ds )return;
	getFilesList();
	var oldFile = FL.fileName(el);
	var This = FL.context(el);
	setTimeout(function(){afterNewFile(This,newFile,ds.to,oldFile,ds.from,pageNumbers);
						 },DELAY_FAST);
}
function newFileFromFile(el,copy){
	var This = FL.context(el);
	var oldFile = This.fileName(el);
	var newFile = trim(prompt((copy?"Copy":"Move")+" page(s) to file:",oldFile)||"");
	if( !newFile )return;
	newFileFromFile.newFile = newFile;
	if( newFile.match(/^[0-9]+$/) )newFile += "_";
	var ds = moveOnServer(0,FL.fileID(el),FL.pageNumbers(el),newFile,PAGES_ALL,copy);
	if( !ds )return;
	getFilesList();
	setTimeout(function(){afterNewFile(This,newFile,ds.to,oldFile,ds.from)},DELAY_FAST);
	// Local
}
function afterNewFile(This,newFile,dsTo,oldFile,dsFrom,pageNumbers){
	var findOld = This.fileByName(new RegExp("^"+oldFile+"$","i"));
	if( findOld )FL.showPages(findOld,dsFrom);
	if( Files ){
		var findNew = Files.fileByName(new RegExp("^"+newFile+"$","i"));
		if( findNew && FL.pagesCont(findNew) )FL.showPages(findNew,dsTo);
		else findNew = null;
	}
	if( pageNumbers )This.afterShow(findOld,findNew,pageNumbers,PAGES_ALL);

}

function deleteFile(ce){
	var This = FL.context(ce);
	var pageNumbers = This.pageNumbers(ce);
	if( !confirm(deleteMessage(This.fileName(ce),pageNumbers)) )return;
	var result = WS(CO("DeleteFile"),This.fileID(ce),pageNumbers);
	if( showSOAPError(result) )return;
	This.showPages(ce,result.value);
	return This.afterShow(ce,null,pageNumbers,sortInt(pageNumbers)[0]);
}
function mailFile(ce){
	var o = showModalDialog("MailSelect.aspx",null,featuresMail);
	if( !(o||{}).to )return;
	var result = WS(CO("MailFile"),o.to,o.subject||"",FL.fileID(ce),FL.pageNumbers(ce));
	showSOAPError(result);
}
function mailFolder(el){
	if( !_applID() )return alert(MSG_NO_APPL_ID);
	var o = showModalDialog("MailSelect.aspx",null,featuresMail);
	if( !o || !o.to )return;
	var result = WS(CO("MailFolder"),o.to,o.subject||"",_applID(),Folders.fileID(el),Folders.pageNumbers(el));
	showSOAPError(result);
}
//************************************** Event handlers **************************************
function clickFile(e){
	e = e || event.srcElement;
	if( this.isFile(e) && !this.showPages(e) )_applID(this.fileName(e));
	var ctrlKey = event.ctrlKey;
	var shiftKey = event.shiftKey;
	this.select(e,undefined,ctrlKey,shiftKey);
	//if( !e )return;
	if( !filesAreApplIDs && this.isFile(e) ){
		if( this.showPages(e) ){
			this.select(e,true);
			return this.showPages(e,false);
		}
		this.showFiles(false);
		this.showPages(e,GetPagesList(this.fileID(e)));
	}
	this.showImages(e);
}
function clickFolder(e){
	e = e||event.srcElement;
	var prevSel = selHist.Get();
	this.select(e,undefined,event.ctrlKey,event.shiftKey);
	if( this.isFile(e) ){
		if( this.showPages(e) && this.pageCount(e) != 0 ){
			this.select(e,true);
			return this.showPages(e,false);
		}
		this.showPages(e,GetPagesList(_applID(),this.fileID(e)));
	}
	this.showImages(e);
}
function clickApplID(e){
	e = e || event.srcElement;
	var applID = this.fileName(e);
	showApplIDPages(applID);
}
function GetPagesList(applID,folderID){
	if( !applID )return alert(MSG_NO_APPL_ID) || false;
	var result = WS(CO("GetPagesList"),applID,folderID||0);
	return showSOAPError(result)?0:result.value;
}
function getFilesList(){
	var ret = WS(CO("GetFilesList"));
	if( showSOAPError(ret) )return;
	updateXmlDSO(xmlFiles,ret.value);
}
//********************************************************************
//****** Virtual event handlers ******
function applID_changed_Attach(foo){
	var vFoos = applID_changed_V.vFoos || [];
	vFoos.push(foo);
	applID_changed_V.vFoos = vFoos;
}
function applID_changed_V(applID){
	applID = applID || _applID();
	Folders.showFiles(false);
	getApplPath(applID);
	var vFoos = applID_changed_V.vFoos || [];
	for( var i=0; i < vFoos.length; i++ )
		vFoos[i](applID);
	// Local
	function getApplPath(applID){
		if( applID )WS(cb,"GetApplPath",applID);
		else _applPath("");
		// Local
		function cb(ret){
			if( showSOAPError(ret) )return;
			_applPath(ret.value[0]);
			var rs = xmlFolders.recordset;
			for(rs.MoveFirst(); !rs.EOF; rs.MoveNext() )
				rs("XmlDSO").value = rs("PagesTable").value = "";
			Folders.hist.Clear();
			updateXmlDSO(xmlFolders,ret.value[1]);
			//setTimeout(function(){
			Folders.colorImageFolders();
			//},100);
		}
	}
}
//****** Properties ******
function _applID(v){
	if( defined(v) ){
		v = v+"";
		var aid = _isFax(v) ? "" : ((v.match(/^([0-9]+)/)||[])[1]||"");
		if( true || txtApplID.prevAID != aid ){
			txtApplID.prevAID = txtApplID.value = aid;
			if( txtApplID.onchange )txtApplID.onchange();
			if( txtApplID.onupdate )txtApplID.onupdate();
		}
	}
	return txtApplID.value || 0;
	// Local
	function _isFax(v){return v.match(/^(\d\d_\d{6}|\d\d\d-\d+)/)}
}
function _applPath(v){
	divApplPath.innerHTML = v;
}
//****** Common ******
function clearSelection(){setTimeout("try{document.selection.empty()}catch(e){}",100);}
function deleteMessage(fileName,pageNumbers){
	var all = pageNumbers[0] == PAGES_ALL ? "ALL " : "";
	var s = pageNumbers.length > 1 || all ? "s" : "";
	var pages = all ? "" : " "+pageNumbers;
	return "Delete "+all+"page"+s+pages+" from \""+fileName+"\"?";
}
//****************************************** Database **********************************************
function addApplicant(fileID,pageID){
var co = ws.createCallOptions("AddApplicant",undefined,false);
var result = ws.Imaging.callService(co,fileID,pageID,1);
	if( showSOAPError(result) )return;
	_applID(result.value);
}
